package com.example.new5.views;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.new5.R;
import com.example.new5.adapter.OlympicAdapter;
import com.example.new5.entity.Olympic;
import com.example.new5.utils.JsonUtils;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
public class OlympicFragment extends Fragment {
    private RecyclerView mRecyclerView;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view= inflater.inflate(R.layout.fragment_olympic, container, false);
        mRecyclerView = view.findViewById(R.id.recyclerView);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        // 解析JSON并填充数据
        List<Olympic> medalDataList = parseJsonToMedalData(getJson("olympic.json"));
        OlympicAdapter adapter = new OlympicAdapter(medalDataList);
        mRecyclerView.setAdapter(adapter);
        return view;
    }
    private List<Olympic> parseJsonToMedalData(String jsonStr) {
        List<Olympic> olympicList = new ArrayList<>();
        JsonObject jo = JsonParser.parseString(jsonStr).getAsJsonObject();
        JsonObject result = jo.get("result").getAsJsonObject();
        JsonArray array = result.get("medalsList").getAsJsonArray();
        for (JsonElement jsonElement : array) {
            JsonObject jsonObject = jsonElement.getAsJsonObject();
            Olympic olympic = new Olympic();
            olympic.setRank(jsonObject.get("rank").getAsString());
            olympic.setCountryid(jsonObject.get("countryid").getAsString());
            olympic.setCountryname(jsonObject.get("countryname").getAsString());
            olympic.setGold(jsonObject.get("gold").getAsString());
            olympic.setSilver(jsonObject.get("silver").getAsString());
            olympic.setBronze(jsonObject.get("bronze").getAsString());
            olympic.setCount(jsonObject.get("count").getAsString());
            olympicList.add(olympic);
        }
        return olympicList;
    }
    private String getJson(String name) {
        String json = JsonUtils.getJsonFromAssets(getContext(), name);
        Log.d("asdf", "getJson = " + json);
        return json;
    }
}